package com.java.base.exercise.guava;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import lombok.SneakyThrows;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author RenPu
 * @Date 2021/7/3 9:48
 * @Version 1.0
 * @Description: 谷歌guava-api的练习
 **/
public class Guava_001 {

//    Cache<String, String> cache = CacheBuilder.newBuilder()
//            .maximumSize(1000)
//            .expireAfterWrite(10, TimeUnit.MINUTES)
//            .build(new CacheLoader<String, String>() {
//                @Override
//                public String load(String key) throws Exception {
//                    return getValueFromDatabase(key);
//                }
//            });


    private static String getValueFromDatabase(String key) {
        System.out.println("load value from database...");
        return "value-" + key;
    }



    @SneakyThrows
    public static void main(String[] args) {
        Cache<String, String> cache = CacheBuilder.newBuilder()
                // 设置缓存大小为1000
                .maximumSize(1000)
                // 设置缓存过期时间随机化
                .expireAfterWrite(10 + new Random().nextInt(5), TimeUnit.MINUTES)
                .build();

        for (int i = 0; i < 100; i++) {
            String key = "key-" + i % 10;
            String value = cache.get(key, () -> getValueFromDatabase(key));
            System.out.println("get from cache: " + value);
            Thread.sleep(100);
        }


    }
}

